import i18n from 'i18next';
import {initReactI18next} from 'react-i18next';
import {i18nApi, LanguageItem} from '../services/api/i18nApi';
import {storage} from '../utils/storage';
import {APP_SETTINGS} from '../config/config';
import {getLocales} from 'react-native-localize';

// Default language resources (fallback)
const resources = {
  'zh-CN': {
    translation: {
      common: {
        more: '更多',
        cancel: '取消',
        selectLanguage: '选择语言',
        networkError: '网络请求异常，请稍后重试',
        welcomeMessage: '欢迎使用!',
        logout: '退出登录',
      },
      login: {
        username: '账号',
        password: '密码',
        loginButton: '登录',
        register: '立即注册',
        forgotPassword: '忘记密码?',
        rememberMe: '记住密码',
        usernameRequired: '用户名不能为空',
        passwordRequired: '密码不能为空',
        failMessage: '登录失败，请检查用户名或密码',
      },
    },
  },
  'en-US': {
    translation: {
      common: {
        more: 'More',
        cancel: 'Cancel',
        selectLanguage: 'Select Language',
        networkError: 'Network error, please try again later',
        welcomeMessage: 'Welcome!',
        logout: 'Logout',
      },
      login: {
        username: 'Username',
        password: 'Password',
        loginButton: 'Login',
        register: 'Register Now',
        forgotPassword: 'Forgot Password?',
        rememberMe: 'Remember Me',
        usernameRequired: 'Username is required',
        passwordRequired: 'Password is required',
        failMessage: 'Login failed, please check your username or password',
      },
    },
  },
};

// Initialize i18next with default settings, we'll update the language later
i18n.use(initReactI18next).init({
  resources,
  lng: APP_SETTINGS.defaultLanguage,
  fallbackLng: APP_SETTINGS.defaultLanguage,
  interpolation: {
    escapeValue: false,
  },
});

// 获取支持的语言列表
export const fetchSupportedLanguages = async (): Promise<LanguageItem[]> => {
  try {
    const response = await i18nApi.getSupportedLanguages();

    if (response.code === 0 && Array.isArray(response.data)) {
      // 处理后端返回的语言列表
      const langList = response.data.map((item: any) => ({
        label: item.label,
        value: item.value,
      }));

      // 缓存语言列表
      await storage.setAsync('supportedLanguages', JSON.stringify(langList));

      return langList;
    }

    throw new Error('Failed to fetch supported languages');
  } catch (error) {
    console.error('Failed to fetch supported languages:', error);

    // 如果有缓存的语言列表则使用缓存
    try {
      const cachedLanguages = await storage.getStringAsync(
        'supportedLanguages',
      );
      if (cachedLanguages) {
        try {
          return JSON.parse(cachedLanguages);
        } catch (e) {
          console.error('Failed to parse cached languages:', e);
        }
      }
    } catch (e) {
      console.error('Failed to get cached languages:', e);
    }

    // 使用i18nApi提供的默认语言列表
    return i18nApi.getDefaultLanguages();
  }
};

// 从后端获取所有语言的翻译资源
export const fetchAllTranslations = async (): Promise<Record<
  string,
  any
> | null> => {
  try {
    console.log('Fetching all translations from server...');
    const response = await i18nApi.getAllTranslations();

    if (response.code === 0 && response.data) {
      const allTranslations = response.data;

      // 缓存所有翻译数据
      storage.set('all_translations', JSON.stringify(allTranslations));
      // 更新i18n资源
      for (const [lang, translations] of Object.entries(allTranslations)) {
        if (translations) {
          i18n.addResourceBundle(lang, 'translation', translations, true, true);
        }
      }

      return allTranslations;
    }

    throw new Error('Failed to fetch all translations');
  } catch (error) {
    console.error('Failed to fetch all translations:', error);
    return null;
  }
};

// 从后端获取特定语言的翻译
export const fetchTranslation = async (lang: string): Promise<any> => {
  try {
    const response = await i18nApi.getTranslation(lang);
    if (response.code === 0 && response.data) {
      const translations = response.data;
      // 更新i18n资源
      i18n.addResourceBundle(lang, 'translation', translations, true, true);

      return translations;
    }

    throw new Error(`Failed to fetch translations for ${lang}`);
  } catch (error) {
    console.error(`Failed to fetch translations for ${lang}:`, error);
    return null;
  }
};

// 初始化国际化
export const initializeI18n = async (lngs: LanguageItem[]) => {
  const currentLanguage = storage.getString(
    'language',
    lngs.find(item => item.value.includes(getLocales()[0].languageCode))
      ?.value ?? 'en-US',
  );
  await changeLanguage(currentLanguage);
};

// 切换语言
export const changeLanguage = async (lang: string) => {
  try {
    // 尝试从缓存加载翻译
    const cachedAllTranslations = storage.getString('all_translations');
    const hasAllTranslationsCache = !!cachedAllTranslations;
    if (hasAllTranslationsCache) {
      // 从全部语言缓存中使用对应语言的翻译
      try {
        const allTranslations = JSON.parse(cachedAllTranslations);
        for (const [key, value] of Object.entries(allTranslations)) {
          i18n.addResourceBundle(key, 'translation', value, true, true);
        }
      } catch (error) {
        // 如果解析失败，尝试获取特定语言的翻译
        await fetchTranslation(lang);
      }
    } else {
      await fetchTranslation(lang);
    }
    i18n.changeLanguage(lang);
    storage.set('language', lang);
    return true;
  } catch (error) {
    console.error(`Failed to change language to ${lang}:`, error);
    return false;
  }
};

export default i18n;
